/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import au.com.bytecode.opencsv.CSVReader;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import au.com.bytecode.opencsv.CSVWriter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
//import net.sf.json.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 *
 * @author Haqim
 */
public class fileUpload extends HttpServlet {
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        response.setContentType("applicatin/json");
        ArrayList<String> stu = new ArrayList<String>();
        ArrayList<String> bid = new ArrayList<String>();
        ArrayList<Course> course = new ArrayList<Course>();
        ArrayList<String> section = new ArrayList<String>();
        ArrayList<String> courseCompleted = new ArrayList<String>();
        ArrayList<String> pre = new ArrayList<String>();
        
        Course c = null;
        
        
        PrintWriter out = response.getWriter();
        
        try {
            ServletFileUpload upload = new ServletFileUpload();
            response.setContentType("text/plain");
            
            FileItemIterator iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();
                
                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                } else {
                    out.println("Got an uploaded file: " + item.getFieldName()
                            + ", name = " + item.getName());
                    
                    if (item.getName().substring(item.getName().length() - 4, item.getName().length()).equalsIgnoreCase(".zip")) {
                        
                        //out.println(" substirg " +  item.getName().substring( item.getName().length() - 4 , item.getName().length()));
                        
                        ZipInputStream zin = new ZipInputStream(new BufferedInputStream(in));
                        
                        //ZipEntry entry;
                        
                        // wrap the ZipInputStream with an InputStreamReader
                        InputStreamReader isr = new InputStreamReader(zin);
                        BufferedReader br = new BufferedReader(isr);
                        ZipEntry ze;
                        
                        String cbs = "";
                        
                        int studentLines = 0;
                        int bidLines = 0;
                        int courseCompletedLines = 0;
                        int courseLines = 0;
                        int prerequisitesLines = 0;
                        int sectionLines = 0;
                        
                        
                        
                        
                        while ((ze = zin.getNextEntry()) != null) {
                            out.println("File name: " + ze);
                            //CSVReader reader = new CSVReader(br,',','`',1);
                            CSVReader reader = new CSVReader(br, ',', '"',1);
                            
                            String[] nextLine;
                            
                            
                            //this is where the csv reaer is fed the next csv file
                            // we shalll write an if loop to detect file name to sort out the different formating of display
                            
                            if (ze.toString().equalsIgnoreCase("bid.csv")) {
                                
                                out.println("WE ARE IN BIDS YO");
                                
                                int kount = 0;
                                
                                
                                //then we shall loop through the 'file'
                                
                                while ((nextLine = reader.readNext()) != null) {
                                    // nextLine[] is an array of values from the line
                                    
                                    //out.println("File name: " + ze);
                                    
                                    if (!nextLine[0].equalsIgnoreCase("userid")) {
                                        
                                        out.println("=========================");
                                        
                                        out.println("Entry number " + kount);
                                        
                                        out.println("UserID: " + nextLine[0].trim());
                                        out.println("Amount: " + nextLine[1]);
                                        out.println("Code: " + nextLine[2].trim());
                                        out.println("Section: " + nextLine[3].trim());
                                        
                                        out.println("=========================");
                                        out.println();
                                        kount += 1; //ruby style
                                        bidLines += 1;
                                        
                                        String csv = nextLine[0].trim() + "," + nextLine[1] + ","
                                                + nextLine[2].trim() + "," + nextLine[3].trim();
                                        
                                        
                                        bid.add(csv);
                                    }
                                }
                                
                            } else if (ze.toString().equalsIgnoreCase("course_completed.csv")) {
                                
                                out.println("WE ARE IN Course Completed YO");
                                
                                int kount = 0;
                                
                                
                                //then we shall loop through the 'file'
                                
                                while ((nextLine = reader.readNext()) != null) {
                                    // nextLine[] is an array of values from the line
                                    
                                    //out.println("File name: " + ze);
                                    
                                    if (!nextLine[0].equalsIgnoreCase("userid")) {
                                        
                                        out.println("=========================");
                                        
                                        out.println("Entry number " + kount);
                                        
                                        out.println("UserID: " + nextLine[0]);
                                        out.println("Code: " + nextLine[1]);
                                        
                                        
                                        out.println("=========================");
                                        out.println();
                                        kount += 1; //ruby style
                                        courseCompletedLines += 1;
                                        
                                        String csv = nextLine[0].trim() + "," + nextLine[1].trim();
                                        
                                        
                                        courseCompleted.add(csv);
                                    }
                                }
                                
                            } else if (ze.toString().equalsIgnoreCase("course.csv")) {
                                
                                out.println("WE ARE IN Course YO");
                                
                                
                                
                                int kount = 0;
                                
                                //then we shall loop through the 'file'
                                
                                while ((nextLine = reader.readNext()) != null) {
                                    
                                    
                                    if (!nextLine[0].equalsIgnoreCase("course")) {
                                        
                                        out.println("=========================");
                                        
                                        out.println("Entry number " + kount);
                                        
                                        out.println("Course: " + nextLine[0]);
                                        out.println("School: " + nextLine[1]);
                                        out.println("Title: " + nextLine[2]);
                                        out.println("Description: " + nextLine[3]);
                                        out.println("Exam Date: " + nextLine[4]);
                                        out.println("Exam Start: " + nextLine[5]);
                                        out.println("Exam End: " + nextLine[6]);
                                        
                                        out.println("=========================");
                                        out.println();
                                        kount += 1; //ruby style
                                        courseLines += 1;
                                        
                                        String rep = nextLine[3].replace("'", "\'");
                                        
                                        c = new Course(
                                                nextLine[0].trim() ,
                                                nextLine[1].trim() ,
                                                nextLine[2] ,
                                                rep,
                                                nextLine[4].trim(),
                                                nextLine[5].trim(),
                                                nextLine[6].trim());
                                        
                                        
                                        
                                        //course.add(csv);
                                    }
                                    
                                    course.add(c);
                                }
                                
                            } else if (ze.toString().equalsIgnoreCase("prerequisite.csv")) {
                                
                                out.println("WE ARE IN Prerequisite YO");
                                
                                int kount = 0;
                                
                                
                                //then we shall loop through the 'file'
                                
                                while ((nextLine = reader.readNext()) != null) {
                                    // nextLine[] is an array of values from the line
                                    
                                    //out.println("File name: " + ze);
                                    
                                    if (!nextLine[0].equalsIgnoreCase("course")) {
                                        
                                        out.println("=========================");
                                        
                                        out.println("Entry number " + kount);
                                        
                                        out.println("Course: " + nextLine[0]);
                                        out.println("Prerequisites: " + nextLine[1]);
                                        
                                        out.println("=========================");
                                        out.println();
                                        kount += 1; //ruby style
                                        prerequisitesLines += 1;
                                        
                                        String csv = nextLine[0].trim() + "," + nextLine[1].trim();
                                        
                                        
                                        pre.add(csv);
                                    }
                                }
                                
                            } else if (ze.toString().equalsIgnoreCase("section.csv")) {
                                
                                out.println("WE ARE IN section YO");
                                
                                int kount = 0;
                                
                                
                                //then we shall loop through the 'file'
                                
                                while ((nextLine = reader.readNext()) != null) {
                                    // nextLine[] is an array of values from the line
                                    
                                    //out.println("File name: " + ze);
                                    
                                    
                                    if (!nextLine[0].equalsIgnoreCase("course")) {
                                        
                                        out.println("=========================");
                                        
                                        out.println("Entry number " + kount);
                                        out.println("Course: " + nextLine[0]);
                                        out.println("Section: " + nextLine[1]);
                                        out.println("Day: " + nextLine[2]);
                                        out.println("Start: " + nextLine[3]);
                                        out.println("End: " + nextLine[4]);
                                        out.println("Instructor: " + nextLine[5]);
                                        out.println("Venue: " + nextLine[6]);
                                        out.println("Size: " + nextLine[7]);
                                        
                                        out.println("=========================");
                                        out.println();
                                        kount += 1; //ruby style
                                        sectionLines += 1;
                                        
                                        String csv = nextLine[0].trim() + "," + nextLine[1].trim() + ","
                                                + nextLine[2].trim() + "," + nextLine[3].trim() + "," + nextLine[4].trim()
                                                + "," + nextLine[5] + "," + nextLine[6].trim() + "," + nextLine[7].trim();
                                        
                                        section.add(csv);
                                        
                                    }
                                }
                                
                            } else if (ze.toString().equalsIgnoreCase("student.csv")) {
                                
                                out.println("WE ARE IN Students YO");
                                
                                //dbFunctions db = new
                                
                                int kount = 0;
                                
                                
                                //then we shall loop through the 'file'
                                
                                while ((nextLine = reader.readNext()) != null) {
                                    if (!nextLine[0].equalsIgnoreCase("userid")) {
                                        
                                        out.println("=========================");
                                        
                                        out.println("Entry number " + kount);
                                        
                                        out.println("UserID: " + nextLine[0]);
                                        out.println("Password: " + nextLine[1]);
                                        out.println("Name: " + nextLine[2]);
                                        out.println("School: " + nextLine[3]);
                                        out.println("eDollar: " + nextLine[4]);
                                        
                                        out.println("=========================");
                                        out.println();
                                        kount += 1; //ruby style
                                        studentLines += 1;
                                        
                                        String csv = nextLine[0].trim() + "," + nextLine[1].trim() + ","
                                                + nextLine[2] + "," + nextLine[3].trim() + "," + nextLine[4].trim();
                                        
                                        stu.add(csv);
                                        
                                    }
                                }
                                
                                out.println("Finished parsing");
                                out.println("=====================");
                            } else {
                                
                                out.println("serious error reading the CSV file. application will now exit");
                                System.exit(0);
                            }
                            
                            
                            
                        }
                        
                        out.println(course.size() + " course szize");
                        
                        for (int i = 0; i < course.size(); i++) {
                            
                            out.println("course " + course.get(i));
                            
                        }
                        //
                        //                        for (int i = 0; i < section.size(); i++) {
                        //
                        //                            out.println("secrtion " + section.get(i));
                        //
                        //                        }
                        
                        
                        System.out.println("--- Emptying Tables ---");
                        dbFunctions.dropTables();
                        System.out.println("--- /Emptying Tables ---");
                        System.out.println("--- Inserting Students ---");
                        
                        dbFunctions.insertStudent(stu);
                        System.out.println("--- /Inserting Students --");
                        
                        System.out.println("--- Inserting Course ---");
                        dbFunctions.insertCourse(course);
                        System.out.println("--- /Inserting course ---");
                        
                        System.out.println("--- Inserting Sections ---");
                        dbFunctions.insertSection(section);
                        System.out.println("--- /Inserting Sectinos --");
                        
                        System.out.println("--- Inserting pre ---");
                        dbFunctions.insertPrerequisites(pre);
                        System.out.println("--- !Inserting pre ---");
                        
                        System.out.println("--- Inserting course completed ---");
                        dbFunctions.insertCourseCompleted(courseCompleted);
                        System.out.println("--- !Inserting course completed ---");
                        
                        System.out.println("--- Inserting bid ---");
                        dbFunctions.insertBid(bid);
                        System.out.println("--- !Inserting bid ---");
                        
                        
                        
                        out.println("++++++++++++++++++++++++++++++++++");
                        out.println("Lines Parsed:");
                        out.println("Courses:" + courseLines);
                        out.println("Prerequisites:" + prerequisitesLines);
                        out.println("Students:" + studentLines);
                        out.println("Bids:" + bidLines);
                        out.println("Sections:" + sectionLines);
                        out.println("Course Completed: " + courseCompletedLines);
                        out.println("++++++++++++++++++++++++++++++++++");
                        
                        
                        in.close();
                        isr.close();
                        br.close();
                        zin.close();
                 
                        Map list1 = new HashMap();
                        list1.put("Prerequisites:" , prerequisitesLines);
                        list1.put("Courses:" , courseLines);
                        list1.put("Students:" , studentLines);
                        list1.put("Bids:" , bidLines);
                        list1.put("Sections:" , sectionLines);
                        list1.put("Course Completed: " , courseCompletedLines);
                        
                        Map map = new HashMap();
                        map.put( "status", "success" );
                        map.put( "num-record", list1 );
                        
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();
                        String s = gson.toJson(map);
                        
                        out.println(s);
                        
                        
                        
                        
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.putAll(map);
                        out.println( jsonObject );
                        
                        
                        
                        //                        obj.t
                        //                        //obj.toJSONString();
                        //
                        //                        out.println(obj.toString());
                        //                        //obj.put(listl);
                        
                        
                        
                        
                        
                        
                        
                    } else {
                        out.println("Unable to process upload. Wrong file formart");
                        System.exit(0);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            // throw new ServletException(ex);
        } finally{
            
            
            
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    //@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
            
            
        } catch (FileUploadException ex) {
            Logger.getLogger(fileUpload.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        
        
        
    }
    
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    // @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
            
            
        } catch (FileUploadException ex) {
            Logger.getLogger(fileUpload.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    //@Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
